package com.example.gaming;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.ajouconqueror.R;
import com.example.ajouconqueror.RequestService;
import com.example.classes.ABuildingInR;
import com.example.classes.BuildingEntity;
import com.example.classes.IP;
import com.example.classes.UserApplication;
import com.example.classes.customLocation;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class conquering extends Activity implements LocationListener, OnMarkerClickListener, Runnable {
	private GoogleMap map;
	
	IP ip = new IP();
	private final String HOST = ip.ip;
	private final int PORT = 8080;
	private final String LOCATION_POST = "/AjouConquerorServer-war/webresources/location";
	private final String BUILDING_GET = "/AjouConquerorServer-war/webresources/building";
	private final String concueredAB_POST = "/AjouConquerorServer-war/webresources/ForGameOver/concueredAB";
	private final String addroom_POST = "/AjouConquerorServer-war/webresources/ForGameOver/addroom";
	private final String STATE_POST = "/AjouConquerorServer-war/webresources/building/state";
	 
	private static final String TAG = "AC";

	int EnterBuildingFlag = 0;
	private String path;
	private boolean flag = true;

	double latitude, longitude;
	private LocationManager locationManager;
	private ArrayList<Marker> markers = new ArrayList<Marker>();
	UserApplication UseApp;
	private static final int REQUEST_ACTING_MISSION = 1;
	Button BuildingButton;
	int TeamNumber;
	int weapon = -1;
	Intent rIntent = null;
	String nowBuilding = null;
	Map<String, ProximityIntentReceiver> receivers = new HashMap<String, ProximityIntentReceiver>();
	boolean mBound = false;
	Thread t = null;
	private ArrayList<ABuildingInR> buildings = new ArrayList<ABuildingInR>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_conquering);
		BuildingButton = (Button) findViewById(R.id.button1);
		BuildingButton.setVisibility(View.INVISIBLE);
		Spinner spinner = (Spinner) findViewById(R.id.spinner1);
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.weapon_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				Toast.makeText(parent.getContext(),
						(CharSequence) parent.getItemAtPosition(pos),
						Toast.LENGTH_SHORT).show();
				weapon = pos;
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		UseApp = (UserApplication) getApplication();
		TeamNumber = UseApp.getTeam();

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
				.getMap();

		if (map != null) {
			map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			map.setOnMarkerClickListener(this);
		}

		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		Location lastLocation = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		addMarkers();
		markers = new ArrayList<Marker>();
		path = BUILDING_GET;
		AsyncGet ag = new AsyncGet();
		ag.execute();
		
		if (lastLocation != null)
			onLocationChanged(lastLocation);

		startService(new Intent(this, RequestService.class));
		
		addbFR addbF = new addbFR();
		addbF.execute();
		t = new Thread(this);
		t.start();
	}

	private class addbFR extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected String doInBackground(String... params) {
			String result = "false";

			int tp=UseApp.getRoomid();
			String p=Integer.toString(tp);
			
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(addroom_POST);
			post.setHeader("Content-Type", "text/plain");
			
			HttpEntity entity = null;
			StringEntity se;
			
			try {
				se = new StringEntity(p);
				post.setEntity(se); 	

				HttpResponse response = client.execute(target, post);

				if (response.getStatusLine().getStatusCode() < 400) {
					Log.d("TAG", "Error in HTTP GET. Status code: "+response.getStatusLine().getStatusCode());
				} 

				entity = response.getEntity();
				String str = EntityUtils.toString(entity);
				result = str;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.i("errorr:", "UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				Log.i("errorr:", "ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				Log.i("errorr:", "IOException");
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(conquering.this, result, Toast.LENGTH_SHORT).show();
		}
	}
	
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				5000, 10, this);
		
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.example.ajouconqueror.GAMEOVER");
		registerReceiver(gameoverReceiver, filter);
	}

	@Override
	protected void onPause() {
		unregisterReceiver(gameoverReceiver);
		locationManager.removeUpdates(this);
		this.stopService(new Intent(this, RequestService.class));
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		Set<String> keySet = receivers.keySet();
		Iterator<String> iterator = keySet.iterator();
		   while (iterator.hasNext()) {
			   String key = iterator.next();
			   ProximityIntentReceiver value = receivers.get(key);
			   receivers.remove(value);
			   unregisterReceiver(value);
		}
		super.onDestroy();
	}
	
	BroadcastReceiver gameoverReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Intent i = new Intent(conquering.this, GameOverActivity.class);
			startActivity(i);

			finish();
		}
	};

	private class AsyncGet extends
			AsyncTask<Void, Void, ArrayList<BuildingEntity>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected ArrayList<BuildingEntity> doInBackground(Void... params) {
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);

			// set the MIME type for POST message body.
			get.setHeader("Content-Type", "application/json");

			HttpEntity entity = null;
			try {
				HttpResponse response = client.execute(target, get);
				Log.d(TAG, "in AsyncGet: "
						+ response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() != 200)
					return null;

				entity = response.getEntity();
				String str = EntityUtils.toString(entity, "utf-8");
				ArrayList<BuildingEntity> be = JSONtoBuilding(str);

				return be;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<BuildingEntity> result) {
			if (result != null) {
				Toast.makeText(getApplicationContext(),
						"Success to get buildings!", Toast.LENGTH_SHORT).show();

				for (BuildingEntity b : result) {
					LatLng latlng = new LatLng(b.getLati(), b.getLongi());
					Marker marker = map.addMarker(new MarkerOptions()
									.position(latlng)
									.title(b.getName())
									.snippet("latitude:" + b.getLati() + "longitude:" + b.getLongi())
									.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
					markers.add(marker);

					long expiration = -1;
					Intent intent = new Intent(b.getName());
					PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
					locationManager.addProximityAlert(b.getLati(), b.getLongi(), 30f, expiration, pi);

					IntentFilter filter = new IntentFilter(b.getName());
					ProximityIntentReceiver pir = new ProximityIntentReceiver();
				    registerReceiver(pir, filter);

					CircleOptions circleOptions = new CircleOptions()
							.center(new LatLng(b.getLati(), b.getLongi()))
							.radius(30f).strokeColor(Color.MAGENTA);
					map.addCircle(circleOptions);

					receivers.put(b.getName(), pir);
				}
			} else {
				Toast.makeText(getApplicationContext(),
						"Fail to get buildings!", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private ArrayList<BuildingEntity> JSONtoBuilding(String json) {
		Gson gson = new Gson();
		Type t = new TypeToken<ArrayList<BuildingEntity>>() {
		}.getType();
		ArrayList<BuildingEntity> be = gson.fromJson(json, t);
		return be;
	}

	@Override
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				5000, 10, this);
		LatLng address = new LatLng(latitude, longitude);
		CameraPosition cp = new CameraPosition.Builder().target((address))
				.zoom(18).build();
		map.animateCamera(CameraUpdateFactory.newCameraPosition(cp));

		customLocation loca = new customLocation(UseApp.getUserid(),
				location.getLatitude(), location.getLongitude());

		path = LOCATION_POST;
		AsyncLocation al = new AsyncLocation();
		al.execute(loca);
	}

	private class AsyncLocation extends
			AsyncTask<customLocation, Void, ArrayList<customLocation>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected ArrayList<customLocation> doInBackground(
				customLocation... params) {
			params[0].setId(UseApp.getUserid());
			String loc = LocToJSON(params[0]);

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(path);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/json");

			StringEntity se;

			try {
				se = new StringEntity(loc, HTTP.UTF_8);
				post.setEntity(se);
				HttpResponse response = client.execute(target, post);
				Log.d(TAG, response.getStatusLine().getStatusCode() + "");
				if (response.getStatusLine().getStatusCode() != 204
						&& response.getStatusLine().getStatusCode() != 200)
					return null;

				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String str = EntityUtils.toString(entity);
					ArrayList<customLocation> users = JSONToLoc(str);
					return users;
				} else
					return null;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<customLocation> result) {
			if (result != null) {
				boolean flag = false;
				for (customLocation u : result) {
					if (u.getId() == null) continue;
					LatLng userlLoc = new LatLng(u.getLatitude(), u.getLongitude());

					for (Marker m : markers) {
						if (m.getTitle() != null && m.getTitle().equals(u.getId())) {
							m.setPosition(userlLoc);
							m.setSnippet("latitude: " + u.getLatitude() + " longitude: " + u.getLongitude());
							flag = true;
							break;
						}
					}
					if (!flag) {
						Marker newMarker = map.addMarker(new MarkerOptions()
								.position(userlLoc)
								.title(u.getId())
								.snippet("latitude: " + u.getLatitude() + "longitude: " + u.getLongitude())
								.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
						markers.add(newMarker);
						flag = false;
					}
				}
			} else {
				Toast.makeText(getApplicationContext(), "Failed!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void addMarkers() {
		LatLng userlLoc = new LatLng(latitude, longitude);
		Marker myMarker = map.addMarker(new MarkerOptions()
				.position(userlLoc)
				.title(UseApp.getUserid())
				.snippet("latitude:" + latitude + " longitude:" + longitude)
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.ic_launcher)));
		markers.add(myMarker);
	}
	
	private ArrayList<customLocation> JSONToLoc(String json) {
		Gson gson = new Gson();
		Type t = new TypeToken<ArrayList<customLocation>>() {
		}.getType();

		ArrayList<customLocation> users = gson.fromJson(json, t);
		return users;
	}

	private String LocToJSON(customLocation cl) {
		Gson gson = new Gson();
		String json = gson.toJson(cl);
		return json;
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	class ProximityIntentReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
				BuildingButton.setVisibility(View.VISIBLE);
				BuildingButton.setText(intent.getAction());
				nowBuilding = intent.getAction();
		}
	}
 
	public void onClick(View v) {
		if (weapon == 0)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission.class), REQUEST_ACTING_MISSION);
		else if (weapon == 1)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission2.class), REQUEST_ACTING_MISSION);
		else if (weapon == 2)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission3.class), REQUEST_ACTING_MISSION);
		else if (weapon == 3)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission4.class), REQUEST_ACTING_MISSION);
		else if (weapon == 4)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission5.class), REQUEST_ACTING_MISSION);
		else if (weapon == 5)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission6.class), REQUEST_ACTING_MISSION);
		else if (weapon == 6)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission7.class), REQUEST_ACTING_MISSION);
		else if (weapon == 7)
			startActivityForResult(new Intent(conquering.this, conqueringActingMission8.class), REQUEST_ACTING_MISSION);
		//		Intent mIntent = null;
//		if (weapon == 0) {
//			mIntent = new Intent(conquering.this, conqueringActingMission.class);
//			Bundle mBundle = new Bundle();
//			for (ABuildingInR b : buildings) {
//				if (b.getBuidlingname().equals(nowBuilding)) {
//					int i = 0;
//					for (int q : b.getQuestions()) {
//						mBundle.putInt(i+"", q);
//						i++;
//					}
//				}
//			}
//			mBundle.putString("building", nowBuilding);
//			mIntent.putExtras(mBundle);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 1) {
//			mIntent = new Intent(conquering.this, conqueringActingMission2.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 2) {
//			mIntent = new Intent(conquering.this, conqueringActingMission3.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 3) {
//			mIntent = new Intent(conquering.this, conqueringActingMission4.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 4) {
//			mIntent = new Intent(conquering.this, conqueringActingMission5.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 5) {
//			mIntent = new Intent(conquering.this, conqueringActingMission6.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 6) {
//			mIntent = new Intent(conquering.this, conqueringActingMission7.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
//		else if (weapon == 7) {
//			mIntent = new Intent(conquering.this, conqueringActingMission8.class);
//			mIntent.putExtra("building", nowBuilding);
//			startActivityForResult(mIntent, REQUEST_ACTING_MISSION);
//		}
	}

	private class concueredAB extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected String doInBackground(String... params) {
			String result = "false";

			String cid=UseApp.getUserid();
			String buildingnatp=Integer.toString(UseApp.getRoomid());
			String roomid=buildingnatp;
			String buildingname=nowBuilding;
			String pointTp=Integer.toString(UseApp.getPoint());
			String Apoint=pointTp;

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(concueredAB_POST);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			HttpEntity entity = null;

			List<NameValuePair> idpair = new ArrayList<NameValuePair>();
			idpair.add(new BasicNameValuePair("uid", cid));
			idpair.add(new BasicNameValuePair("roomid", roomid));
			idpair.add(new BasicNameValuePair("buildingname", buildingname));
			idpair.add(new BasicNameValuePair("point", Apoint));
			
			try {
				post.setEntity(new UrlEncodedFormEntity(idpair));

				HttpResponse response = client.execute(target, post);

				// Status code 204 is success with "No content".
				// This happens when a RESTful method returns void.
				if (response.getStatusLine().getStatusCode() < 400) {
					result = "get";
				} 

				entity = response.getEntity();

				String str = EntityUtils.toString(entity);

				result = str;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.i("errorr:", "UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				Log.i("errorr:", "ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				Log.i("errorr:", "IOException");
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {

			Toast.makeText(conquering.this, "You conquered"+result, Toast.LENGTH_SHORT).show();
			UseApp.setPoint(0);
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_ACTING_MISSION) {
				Marker cMarker = null;
				int remove = -1;
				for (int i=0; i<markers.size(); i++) {
					Marker m = markers.get(i);
					if (m.getTitle() != null && m.getTitle().equals(nowBuilding)) {
						ProximityIntentReceiver p = receivers.get(nowBuilding);
						receivers.remove(nowBuilding);
						if (p != null)
							unregisterReceiver(p);
						
						remove = i;
						concueredAB cab = new concueredAB();
						cab.execute();
						
						if (TeamNumber == 1) {
							cMarker = map.addMarker(new MarkerOptions()
											.position(m.getPosition())
											.title(m.getTitle())
											.snippet("Team " + TeamNumber + " conquered!")
											.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
						} else {
							cMarker = map.addMarker(new MarkerOptions()
											.position(m.getPosition())
											.title(m.getTitle())
											.snippet("Team " + TeamNumber + " conquered!")
											.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
						}
						BuildingButton.setVisibility(View.INVISIBLE);
						break;
					}
				}
				if (remove != -1) {
					Marker m = markers.get(remove);
					markers.remove(remove);
					m.remove();
					markers.add(cMarker);
				}
			}
		}
	}
	
	private class AsyncState extends AsyncTask<Void, Void, ArrayList<ABuildingInR>> {
		@Override
		protected ArrayList<ABuildingInR> doInBackground(Void... params) {
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(STATE_POST);

			post.setHeader("Content-Type", "application/json");
			String str = StringtoJSON(UseApp.getRoomid()+"");

			HttpEntity entity = null;
			StringEntity se;
			try {
				se = new StringEntity(UseApp.getRoomid()+"", HTTP.UTF_8);
				post.setEntity(se);
				HttpResponse response = client.execute(target, post);
				Log.d(TAG, "in AsyncState: "
						+ response.getStatusLine().getStatusCode());

				if (response.getStatusLine().getStatusCode() == 200) {
					entity = response.getEntity();
					str = EntityUtils.toString(entity, "utf-8");
					ArrayList<ABuildingInR> array = JSONtoB(str);
					Log.d(TAG, str);
					return array;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(ArrayList<ABuildingInR> result) {
			super.onPostExecute(result);
			if (result != null) {
				buildings.clear();
				for (ABuildingInR a : result) {
					buildings.add(a);
					if (a.getConqueredUId() == null || a.getConqueredUId().equals(UseApp.getUserid())) {
						continue;
					}
					if (a.getConqueredUId().equals(UseApp.getTeam2_M1()) || a.getConqueredUId().equals(UseApp.getTeam2_M2())) {
						Marker cMarker = null;
						for (int i=0; i<markers.size(); i++) {
							Marker m = markers.get(i);
							
							if (m.getTitle() != null && m.getTitle().equals(a.getBuidlingname())) {
								cMarker = map.addMarker(new MarkerOptions().position(m.getPosition())
													.title(m.getTitle())
													.snippet("Team 2 conquered!")
													.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
								markers.remove(m);
								m.remove();
								markers.add(cMarker);
								break;
							}
						}
					} else if (a.getConqueredUId().equals(UseApp.getTeam1_M1()) || a.getConqueredUId().equals(UseApp.getTeam1_M2())) {
						Marker cMarker = null;
						for (int i=0; i<markers.size(); i++) {
							Marker m = markers.get(i);
							if (m.getTitle() != null && m.getTitle().equals(a.getBuidlingname())) {
								cMarker = map.addMarker(new MarkerOptions().position(m.getPosition())
													.title(m.getTitle())
													.snippet("Team 1 conquered!")
													.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
								markers.remove(m);
								m.remove();
								markers.add(cMarker);
								break;
							}
						}
					}
				}
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
	}	

	private String StringtoJSON(String roomid) {
		Gson gson = new Gson();
		String json = gson.toJson(roomid);
		return json;
	}

	private ArrayList<ABuildingInR> JSONtoB(String json) {
		Gson gson = new Gson();
		Type t = new TypeToken<ArrayList<ABuildingInR>>() {
		}.getType();
		ArrayList<ABuildingInR> a = gson.fromJson(json, t);
		return a;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			AsyncState as = new AsyncState();
			as.execute();

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
